﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Sms
{
    /// <summary>
    /// 短消息
    /// </summary>
    public class SmsApi
    {
        private readonly string _smsTemplet;

        /// <summary>
        /// 短消息
        /// </summary>
        public SmsApi()
        {
            _smsTemplet = ConfigurationManager.AppSettings["SmsText"];
            if (_smsTemplet == null)
            {
                throw new InvalidCastException("未在配置文件中找到短信设置SmsText");
            }
        }

        /// <summary>
        /// 发送短消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public int Send(string phone, string message)
        {
            string url = _smsTemplet.Trim().Replace("$phone", phone).Replace("$vc", message);
            string strRet;

            try
            {
                HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(url);
                hr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
                hr.Method = "GET";
                hr.Timeout = 3 * 60 * 1000;
                WebResponse hs = hr.GetResponse();
                Stream sr = hs.GetResponseStream();
                if (sr == null)
                {
                    return 0;
                }
                StreamReader ser = new StreamReader(sr, Encoding.Default);
                strRet = ser.ReadToEnd();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{DateTime.Now} SendSms :{ex}");
                //  LogProvider.Write("VerificationCode SendSms()", LogMessageType.Error, ex);
                return 0;
            }
            return int.Parse(strRet);
        }


      
    }
}
